import { defineStore } from 'pinia'
import axios from 'axios'

export interface DeploymentConfig {
  id?: string
  projectName: string
  repoUrl: string
  branch: string
  deployPath: string
  buildCommand: string
  preDeployCommand?: string
  postDeployCommand?: string
  status?: string
  createdAt?: string
  updatedAt?: string
}

export const useDeploymentStore = defineStore('deployment', {
  state: () => ({
    deployments: [] as DeploymentConfig[],
    loading: false
  }),

  actions: {
    async getDeployments(): Promise<DeploymentConfig[]> {
      try {
        const response = await axios.get('/api/deployments')
        this.deployments = response.data
        return response.data
      } catch (error) {
        console.error('获取部署列表失败:', error)
        throw error
      }
    },

    async createDeployment(config: DeploymentConfig): Promise<void> {
      try {
        const response = await axios.post('/api/deployments', config)
        this.deployments.push(response.data)
      } catch (error) {
        console.error('创建部署失败:', error)
        throw error
      }
    },

    async updateDeployment(id: string, config: DeploymentConfig): Promise<void> {
      try {
        const response = await axios.put(`/api/deployments/${id}`, config)
        const index = this.deployments.findIndex(d => d.id === id)
        if (index !== -1) {
          this.deployments[index] = response.data
        }
      } catch (error) {
        console.error('更新部署失败:', error)
        throw error
      }
    },

    async deployProject(id: string): Promise<void> {
      try {
        await axios.post(`/api/deployments/${id}/deploy`)
      } catch (error) {
        console.error('部署项目失败:', error)
        throw error
      }
    },

    async deleteDeployment(id: string): Promise<void> {
      try {
        await axios.delete(`/api/deployments/${id}`)
        this.deployments = this.deployments.filter(d => d.id !== id)
      } catch (error) {
        console.error('删除部署失败:', error)
        throw error
      }
    },

    async getStats(): Promise<any> {
      try {
        const response = await axios.get('/api/deployments/stats')
        return response.data
      } catch (error) {
        console.error('获取统计信息失败:', error)
        throw error
      }
    },

    async getLogs(): Promise<any[]> {
      try {
        const response = await axios.get('/api/deployments/logs')
        return response.data
      } catch (error) {
        console.error('获取日志失败:', error)
        throw error
      }
    },

    async getProjectLogs(id: string, limit: number = 50): Promise<any[]> {
      try {
        const response = await axios.get(`/api/deployments/${id}/logs?limit=${limit}`)
        return response.data
      } catch (error) {
        console.error('获取项目日志失败:', error)
        throw error
      }
    }
  }
})
